
import os, _pg
import project


def createTables(db):
    q = """
CREATE TABLE Files(
	FileID		serial		NOT NULL,
	DateTime	timestamp(2)  	NOT NULL,
	RepID	int		references RepUsers(RepID) 	NOT NULL,
	FileName	varchar(1024)	NOT NULL,
	Revision	varchar(50)	NOT NULL,
	sourcefile	boolean		NOT NULL default false,
	codelines int,
    commentlines int,
    inlinecommentlines int,
    parent int references Files(FileID),
PRIMARY KEY  (FileID)
);
"""
    dropq = """
drop table Files cascade;
"""
    try:
        print "cleaning File table..."
        db.query(dropq)
        print "...OK!"
    except _pg.ProgrammingError:
            print "could not drop table"
    try:
        print "creating File table..."
        db.query(q)
        print "...OK!"
    except _pg.ProgrammingError, e:
        print "could not create table"
        raise project.ProjectError("Could not create table, cause:" + str(e))


def start(proj, log):
    db = proj.getDatabase()
    createTables(db)
    log.write("Rebuilding files table...")
    repo = proj.getSVNRepository()
    repo.buildFiles(db, log)
    log.write("Files table built and populated.")
           
